import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Table, Tag, DatePicker, Space, message } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { getAttendanceHistory, checkIn, checkOut } from '../../api/attendance';

const { RangePicker } = DatePicker;

/**
 * 员工考勤页面
 * 包含打卡功能和考勤记录查看
 */
const EmployeeAttendance = () => {
    const [loading, setLoading] = useState(false);
    const [attendanceData, setAttendanceData] = useState([]);
    const [dateRange, setDateRange] = useState([]);
    const [todayRecord, setTodayRecord] = useState(null);

    useEffect(() => {
        checkTodayAttendance();
    }, []);

    // 检查今日考勤状态
    const checkTodayAttendance = async () => {
        try {
            const today = new Date().toISOString().split('T')[0];
            const response = await getAttendanceHistory({
                startDate: today,
                endDate: today
            });

            if (response.data && response.data.length > 0) {
                setTodayRecord(response.data[0]);
            }
        } catch (error) {
            console.error('获取今日考勤状态失败:', error);
        }
    };

    // 签到
    const handleCheckIn = async () => {
        try {
            await checkIn();
            message.success('签到成功');
            checkTodayAttendance();
        } catch (error) {
            console.error('签到失败:', error);
            message.error('签到失败');
        }
    };

    // 签退
    const handleCheckOut = async () => {
        try {
            await checkOut();
            message.success('签退成功');
            checkTodayAttendance();
        } catch (error) {
            console.error('签退失败:', error);
            message.error('签退失败');
        }
    };

    // 获取考勤记录
    const fetchAttendanceData = async () => {
        if (!dateRange[0] || !dateRange[1]) {
            message.warning('请选择日期范围');
            return;
        }

        setLoading(true);
        try {
            const response = await getAttendanceHistory({
                startDate: dateRange[0].format('YYYY-MM-DD'),
                endDate: dateRange[1].format('YYYY-MM-DD')
            });

            setAttendanceData(response.data || []);
        } catch (error) {
            console.error('获取考勤记录失败:', error);
            message.error('获取考勤记录失败');
        } finally {
            setLoading(false);
        }
    };

    // 考勤状态映射
    const statusMap = {
        1: { text: '未打卡', color: 'default' },
        2: { text: '正常', color: 'success' },
        3: { text: '迟到', color: 'warning' },
        4: { text: '早退', color: 'warning' },
        5: { text: '缺勤', color: 'error' },
    };

    // 表格列定义
    const columns = [
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            sorter: (a, b) => new Date(a.date) - new Date(b.date),
        },
        {
            title: '签到时间',
            dataIndex: 'checkInTime',
            key: 'checkInTime',
        },
        {
            title: '签退时间',
            dataIndex: 'checkOutTime',
            key: 'checkOutTime',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <Tag color={statusMap[status]?.color}>
                    {statusMap[status]?.text}
                </Tag>
            ),
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
    ];

    return (
        <div>
            <Card title="今日打卡" style={{ marginBottom: 16 }}>
                <Row gutter={16}>
                    <Col span={12}>
                        <Button
                            type="primary"
                            icon={<CheckCircleOutlined />}
                            onClick={handleCheckIn}
                            disabled={todayRecord?.checkInTime}
                            block
                        >
                            签到
                        </Button>
                        {todayRecord?.checkInTime && (
                            <div style={{ marginTop: 8, textAlign: 'center' }}>
                                签到时间：{todayRecord.checkInTime}
                            </div>
                        )}
                    </Col>
                    <Col span={12}>
                        <Button
                            type="primary"
                            icon={<ClockCircleOutlined />}
                            onClick={handleCheckOut}
                            disabled={!todayRecord?.checkInTime || todayRecord?.checkOutTime}
                            block
                        >
                            签退
                        </Button>
                        {todayRecord?.checkOutTime && (
                            <div style={{ marginTop: 8, textAlign: 'center' }}>
                                签退时间：{todayRecord.checkOutTime}
                            </div>
                        )}
                    </Col>
                </Row>
            </Card>

            <Card title="考勤记录">
                <Space style={{ marginBottom: 16 }}>
                    <RangePicker
                        onChange={(dates) => setDateRange(dates)}
                        value={dateRange}
                    />
                    <Button type="primary" onClick={fetchAttendanceData}>
                        查询
                    </Button>
                </Space>

                <Table
                    columns={columns}
                    dataSource={attendanceData}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条记录`,
                    }}
                />
            </Card>
        </div>
    );
};

export default EmployeeAttendance;